package com.xl.ssh.handler;


import com.xl.ssh.constants.Constants;
import com.xl.ssh.service.WebSSHService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

/**
 *
 */
@Component
public class SSHWebSocketHandler implements WebSocketHandler {

    /**
     * 问题，这里所有方法的WebSocketSession是同一个对象吗？ 经过验证却是事实同一个session对象
     */
    @Autowired
    private WebSSHService webSSHService;

    /**
     * 可以通过session向客户端发送消息
     * 连接成功后，封装建立shell通道的参数
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("用户uuid：" + session.getAttributes().get(Constants.USER_UUID_KEY));
        webSSHService.initConnection(session);
    }

    /**
     * 建立连接并发送请求
     *
     * @param message
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> message) throws Exception {
        if (message instanceof TextMessage) {
            webSSHService.recvHandle(((TextMessage) message).getPayload(), webSocketSession);
            //如果是其他类型的数据，不处理
        } else if (message instanceof BinaryMessage) {
            webSocketSession.sendMessage(new TextMessage("不支持二进制指令".getBytes()));
        } else if (message instanceof PongMessage) {
            webSocketSession.sendMessage(new TextMessage("操作指令无法识别".getBytes()));
        } else {
            webSocketSession.sendMessage(new TextMessage("操作指令无法识别".getBytes()));
        }

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.err.println("webSSH数据传输错误");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        System.out.println("用户：" + session.getAttributes().get(Constants.USER_UUID_KEY) + "|" +
                session.getAttributes().get(Constants.USER_INFO_KEY) + "连接断开");
        webSSHService.close(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
